<template>
  <div>
    <tag-content-header>
      <template #title>
        <span>历史覆盖客户数</span>
        <p class="tag-stats-users-tip" v-if="list.length">(最新数据日期: {{ list[list.length - 1].snapshotDate }})</p>
      </template>
      <template #tools>
        <span class="stats-title">时间范围</span>
        <el-radio-group v-model="users.intervalDay" size="mini">
          <el-radio-button :label="7">最近7天</el-radio-button>
          <el-radio-button :label="15">最近15天</el-radio-button>
          <el-radio-button :label="30">最近30天</el-radio-button>
          <el-radio-button :label="999">最近两年</el-radio-button>
        </el-radio-group>
        <!-- <span class="stats-title">客户范围</span>
        <el-select v-model="users.orgId" filterable>
          <el-option
            v-for="item in orgs"
            :key="item.compOrgCode"
            :label="item.compNm"
            :value="item.compOrgCode"
          ></el-option>
        </el-select> -->
      </template>
    </tag-content-header>
    <div class="tag-stats-users">
      <div v-if="list.length || loading">
        <div id="tag-stats-users" class="tag-stats-chart"></div>
      </div>
      <div class="tag-stats-chart" v-else>
        <div class="no-record">
          <img src="~@/assets/img/no_records.png" alt="" /><br />
          暂无数据
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
    assetId: {
      type: String,
      required: true,
      default: ''
    },
    orgs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      users: {
        intervalDay: 7,
        orgId: 0
      },
      loading: false,
      list: [],
      chart: null
    }
  },
  watch: {
    users: {
      handler() {
        this.getSummary()
      },
      deep: true
    }
  },
  methods: {
    getSummary() {
      if (this.loading) return
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('index/supermarket/getMonSummary'),
        method: 'get',
        params: this.$ajax.setParams({
          intervalDay: this.users.intervalDay,
          // orgId: this.users.orgId,
          orgId: 999,
          tagId: this.assetId
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.list = data.data
          this.$nextTick(() => {
            if (this.list.length) {
              this.setChart()
            } else {
              this.chart = null
            }
          })
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getDay(day) {
      let today = new Date()
      let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
      today.setTime(targetday_milliseconds)
      let tYear = today.getFullYear()
      let tMonth = today.getMonth()
      let tDate = today.getDate()

      tMonth = this.doHandleZero(tMonth + 1)
      tDate = this.doHandleZero(tDate)
      return tYear + '-' + tMonth + '-' + tDate
    },
    getLastDayByMonth(monthNum) {
      let dateArr = []
      let today = new Date()
      let year = today.getFullYear()
      let month = today.getMonth() + 1
      let date = today.getDate()
      for (let i = 0; i < monthNum; i++) {
        let tyear = year
        let tmonth = month - i
        if (tmonth <= 0) {
          tyear =
            parseInt(tyear) - Math.ceil(Math.abs(tmonth) == 0 ? 1 : parseInt((Math.abs(tmonth) / 12).toFixed(2)) + 1)
          tmonth = 12 - Math.abs(tmonth % 12)
        }
        dateArr.push(
          tyear +
            '-' +
            this.doHandleZero(tmonth) +
            '-' +
            (i === 0 ? this.doHandleZero(date) : new Date(new Date(tyear, tmonth, 0)).getDate())
        )
      }
      return dateArr.reverse()
    },
    doHandleZero(value) {
      let m = value
      if (value.toString().length === 1) {
        m = '0' + value
      }
      return m
    },
    setChart() {
      var target = document.getElementById('tag-stats-users')
      if (!target) return
      if (!this.chart) this.chart = echarts.init(target)
      let xAxis = []
      let yAxis = []
      let fullDate = []
      if (this.users.intervalDay === 999) {
        // 最近两年，只显示每个月最后一天
        this.getLastDayByMonth()
        fullDate.push(...this.getLastDayByMonth(24))
      } else {
        for (let i = 0; i < this.users.intervalDay; i++) {
          // this.getDay(-7 + i)
          fullDate.push(this.getDay(-this.users.intervalDay + i))
        }
      }
      this.list.forEach(item => {
        xAxis.push(item.snapshotDate)
        yAxis.push(item.tagCoverCount)
      })
      fullDate.forEach((date, index) => {
        if (!xAxis.includes(date)) {
          xAxis.splice(index, 0, date)
          yAxis.splice(index, 0, '')
        }
      })
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          top: '20',
          left: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisLabel: {
              show: true,
              interval: 0,
              rotate: fullDate.length > 15 ? 30 : 0,
              color: '#666'
            },
            axisLine: {
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: false
            },
            data: xAxis
          }
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#666'
            }
          },
          axisTick: {
            inside: true,
            lineStyle: {
              color: '#eee'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#eee'
            }
          }
        },
        series: [
          {
            type: 'bar',
            barWidth: yAxis.length >= 30 ? null : 30,
            data: yAxis,
            itemStyle: {
              color: '#0f80ff'
            },
            label: {
              normal: {
                show: true,
                position: 'top',
                color: '#666'
              }
            }
          }
        ]
      }
      this.chart.setOption(option, true)
      window.addEventListener('resize', () => {
        this.chart.resize()
      })
    },
    reset() {
      this.users.intervalDay = 7
      // this.users.orgId = this.orgs[0].compOrgCode
      this.getSummary()
    }
  }
}
</script>

<style lang="scss">
.tag-stats-users-tip {
  display: inline-block;
  font-size: 14px;
  vertical-align: bottom;
  color: #ff9900;
}
.tag-stats-users {
  margin-bottom: 50px;
  .no-record {
    font-size: 20px;
    height: 100%;
    text-align: center;
    padding-top: 80px;
    img {
      margin-bottom: 10px;
    }
  }
}
</style>
